/**
 * Title: UploadHttpResponseHandler.java
 * Description:
 * Copyright: Copyright (c) 2008
 * Company:深圳彩讯科技有限公司
 * Author 罗旭东 (hi@luoxudong.com)
 * Date 2013-8-9 下午5:20:21
 * Version 1.0 
 */
package com.luoxudong.phonenumber.service.net.http.asynchttp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.luoxudong.phonenumber.service.exception.PhoneNumberException;
import com.luoxudong.phonenumber.service.exception.PhoneNumberExceptionCode;
import com.luoxudong.phonenumber.service.net.http.filetransfer.interfaces.IUploadListener;
import com.luoxudong.phonenumber.service.net.http.filetransfer.manager.UploadManager;
import com.luoxudong.phonenumber.service.net.http.filetransfer.vo.UploadData;
import com.luoxudong.phonenumber.service.net.http.httpclient.Header;
import com.luoxudong.phonenumber.service.net.http.httpclient.HttpStatus;
import com.luoxudong.phonenumber.service.utils.EvtLog;

/** 
 * ClassName: UploadHttpResponseHandler 
 * Description:上传结果回调
 * Create by 罗旭东
 * Date 2013-8-9 下午5:20:21 
 */
public class UploadHttpResponseHandler extends BinaryHttpResponseHandler{
	private static final String TAG = "UploadHttpResponseHandler";
	/**
	 * 写数据流的buffer大小
	 */
	private static final int BUFFER_SIZE = 100 * 1024;
	
	/**
	 * 上传监听
	 */
	private List<IUploadListener> uploadListeners = null;
	
	/**
	 * 是否上传完成
	 */
	private boolean isUploadFinish = false;
	
	public UploadHttpResponseHandler(int uploadId, List<IUploadListener> uploadListeners) {
		super(uploadId);
		this.uploadListeners = uploadListeners;
	}

	@Override
	public void onFailure(int errorCode, String errorMsg, Throwable e) {
		EvtLog.e(TAG, "上传失败!!!!!");
		
		if (uploadListeners != null)
		{
			for (IUploadListener uploadListener : uploadListeners)
			{
				uploadListener.onUploadFail(transferId, errorCode, errorMsg);
			}
		}
		
		onTransferFinish();
		
	}
	
	@Override
	protected void onTransferSuccess() {
		EvtLog.e(TAG, "上传完成!!!!!");
		onTransferFinish();
		
		if (uploadListeners != null)
		{
			for (IUploadListener uploadListener : uploadListeners)
			{
				uploadListener.onUploadSuccess(transferId);
			}
		}
	}
	
	@Override
	protected void onTransferFinish() {
		UploadManager.removeUploadTask(transferId);
	}
	
	@Override
	protected void onTransferPause() {
		// 传输暂停
		EvtLog.e(TAG, "停止上传!!!!!");
		onTransferFinish();
	}
	
	@Override
	protected void onTransferStart() {
		if (uploadListeners != null)
		{
			for (IUploadListener uploadListener : uploadListeners)
			{
				uploadListener.onStartUpload(transferId);
			}
		}
	}
	
	@Override
	public void onSuccess(int statusCode, Header[] headers, String content) {
		if (statusCode != HttpStatus.SC_OK)
		{
			onFailure(PhoneNumberExceptionCode.defaultExceptionCode.getErrorCode(), new PhoneNumberException("http请求失败!"));
			return;
		}
	}
	
	public UploadData initUploadData()
	{
		UploadData uploadData = new UploadData();
		long uploadedSize = 0;
		
		uploadData.setStartOffset(uploadedSize);
		uploadData.setBlockSize(-1);
		uploadData.setUploadStringParams(getUploadStringParams());
		
		return uploadData;
	}
	
	/**
	 * 上传是传送给服务器的参数
	 * @return
	 */
	private Map<String, String> getUploadStringParams()
	{
		Map<String, String> paramsMap = new HashMap<String, String>();
		
		return paramsMap;
	}
	
	public void writeTo(OutputStream out, File file, long startOffset, long blockSize)
	{
		byte[] buffer = new byte[BUFFER_SIZE];
		long readedLen = 0;
		int length = 0;
		
		//随机读取本地文件
		RandomAccessFile randomAccessFile = null;
		try {
			randomAccessFile = new RandomAccessFile(file, "r");
			randomAccessFile.seek(startOffset);
		} catch (FileNotFoundException e) {
			onFailure(PhoneNumberExceptionCode.defaultExceptionCode.getErrorCode(), e);
			return;
		} catch (IOException e) {
			onFailure(PhoneNumberExceptionCode.defaultExceptionCode.getErrorCode(), e);
			return;
		}
		
		EvtLog.d(TAG, "从" + startOffset + "位置开始上传...");
		readedLen = 0;
		int writeLen = 0;
		long totalLength = file.length();
		while(readedLen < blockSize)
		{
			if (blockSize - readedLen > BUFFER_SIZE)
			{
				writeLen = BUFFER_SIZE;
			}
			else
			{
				writeLen = (int)(blockSize - readedLen);
			}
			try {
				length = randomAccessFile.read(buffer);
			} catch (IOException e) {
				onFailure(PhoneNumberExceptionCode.defaultExceptionCode.getErrorCode(), e);
				if (randomAccessFile != null)
				{
					try {
						randomAccessFile.close();
					} catch (IOException e1) {
					}
				}
				return;
			}
			
			if (length < writeLen)
			{
				writeLen = length;
				EvtLog.e(TAG, "块大小错误!");
			}
			
			try {
				out.write(buffer, 0, writeLen);
			} catch (IOException e) {
				onFailure(PhoneNumberExceptionCode.defaultExceptionCode.getErrorCode(), e);
				if (randomAccessFile != null)
				{
					try {
						randomAccessFile.close();
					} catch (IOException e1) {
					}
				}
				return;
			}
			
			readedLen += writeLen;
			
			EvtLog.d(TAG, "已上传大小【已传大小:" + (startOffset + readedLen) + "==块大小:" + blockSize + "==总大小" + totalLength + "】");
			
			if (uploadListeners != null)
			{
				for (IUploadListener listener : uploadListeners)
				{
					listener.onUploading(transferId, startOffset + readedLen, totalLength);
				}
			}
			
			try {
				out.flush();
			} catch (IOException e) {
			}
		}
		
		EvtLog.d(TAG, "已上传大小readedLen:" + readedLen);
		
		try {
			if (randomAccessFile != null)
			{
				randomAccessFile.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
